package com.benbi.shequapi.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.benbi.shequapi.bean.*;
import com.benbi.shequapi.mapper.*;
import com.benbi.shequapi.service.PersonService;
import com.benbi.shequapi.utils.Result;
import com.benbi.shequapi.utils.ResultData;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class PersonImpl implements PersonService {
    @Resource
    PersonMapper personMapper;
    @Resource
    AdminMapper adminMapper;
    @Resource
    WorkerMapper workerMapper;
    @Resource
    ResidentMapper residentMapper;
    @Resource
    BuildingMapper buildingMapper;
    @Resource
    LiveinMapper liveinMapper;
    @Resource
    BuildinMapper buildinMapper;
    @Resource
    PtypeMapper ptypeMapper;
    @Resource
    CommunityMapper communityMapper;

    @Override
    public Result getPersonById(int pid) {
        Person p =  personMapper.selectPersonById(pid);
        if (p == null) {return new Result(1, "不存在该用户");}
        return new ResultData(p);
    }

    @Override
    public Result getPersonByPhone(String phone) {
        Person p = personMapper.selectPersonByPhone(phone);
        if (p == null) {return new Result(1, "不存在该用户");}
        return new ResultData(p);
    }

    @Override
    public Result personLogin(String account, String password, int type) {
        Person p;
        if(account.length() == 11){
            p = personMapper.selectPersonByPhone(account);
        }else {
            p = personMapper.selectPersonById(Integer.parseInt(account));
        }
        if (p == null){ return new Result(1, "用户不存在"); }

        Ptype pt = ptypeMapper.selectPtypeByPid(p.getPid());
        if (pt == null){ return new Result(4, "未知错误"); }
        //校验用户类型，管理员和工作人员共享登录页面
        int realType = pt.getGid();
        switch(type){
            case 1:
                if (realType != 1){ return new Result(1, "用户不存在"); }
                break;
            case 2:
                if (realType != 2 && realType != 1){ return new Result(1, "用户不存在"); }
                break;
            case 3:
                if (realType != 3){ return new Result(1, "用户不存在"); }
                break;
            default:
                return new Result(3, "用户类型不存在");
        }

        if (p.getPassword().equals(password)){
            JSONObject jsonObject = (JSONObject)JSONObject.toJSON(p);
            jsonObject.put("ptype", realType);
            return new ResultData(0, "登录成功", jsonObject);
        }else {
            return new Result(2, "密码错误");
        }

    }

    @Override
    public Result personSignup(int type, String phone, String password, String name, String civilId, int gender, Date birthdate, String bno, String room, int cid) {

        //检测居住房间合法性
        Building b = null;
        if (type == 3){
            b = buildingMapper.selectBuildingByBno(bno);
            if (b == null){
                return new Result(4, "楼栋不存在");
            }
            Buildin bi = buildinMapper.selectBuildinByCidBid(cid, b.getBid());
            if (bi == null){
                return new Result(4, "楼栋不存在");
            }
        }

        Person p = new Person(phone, password, name, civilId, gender, birthdate);
        p.setInDate(new Date());
        int pid;
        try {
            if(personMapper.insertPerson(p) == 0){
                return new Result(2, "未知错误");
            }
            pid = p.getPid();
            switch (type){
                case 1:
                    adminMapper.insertAdmin(new Admin(pid));
                    ptypeMapper.replaceIntoPtype(new Ptype(pid, 1));
                    break;
                case 2:
                    workerMapper.insertWorker(new Worker(pid));
                    ptypeMapper.replaceIntoPtype(new Ptype(pid, 2));
                    break;
                case 3:
                    residentMapper.insertResident(new Resident(pid));
                    ptypeMapper.replaceIntoPtype(new Ptype(pid, 3));
                    break;
                default:
                    return new Result(3, "不存在的用户类型");
            }
        }catch (DuplicateKeyException e){
            return new Result(1, "手机号已被注册");
        }

        //添加居住
        if (type == 3){
            liveinMapper.insertLivein(new Livein(pid, b.getBid(), room));
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("pid", pid);
        return new ResultData(0, "注册成功", jsonObject);
    }

    @Override
    public Result queryPerson(String keyword, int mode) {
        List<Person> resultList;
        try{
            switch (mode){
                //按id
                case 0:
                    int pid = Integer.parseInt(keyword);
                    Person p = personMapper.selectPersonById(pid);
                    if (p == null) {return new Result(3, "未查询到相关人员");}
                    resultList = new ArrayList<Person>();
                    resultList.add(p);
                    break;
                //按姓名
                case 1:
                    resultList = personMapper.selectPersonByNameSubString(keyword);
                    if (resultList.isEmpty()) {return new Result(3, "未查询到相关人员");}
                    break;
                //按手机号
                case 2:
                    p = personMapper.selectPersonByPhone(keyword);
                    if (p == null) {return new Result(3, "未查询到相关人员");}
                    resultList = new ArrayList<Person>();
                    resultList.add(p);
                    break;
                default:
                    return new Result(5, "无此查询模式");
            }
        }catch (NumberFormatException e){
            return new Result(4, "输入有误");
        }

        JSONArray jsonArray = new JSONArray();
        for (Person person : resultList) {
            Ptype pt = ptypeMapper.selectPtypeByPid(person.getPid());
            if (pt == null) {return new Result(2, "未知错误");}

            JSONObject jsonObject = new JSONObject();
            jsonObject.putAll((JSONObject) JSONObject.toJSON(person));
            jsonObject.put("ptype", pt.getGid());
            //居民返回额外信息
            if (pt.getGid() == 3){
                ResultData addrResultData = ServiceUtil.getLiveAddrByPid(liveinMapper, buildingMapper, buildinMapper, communityMapper, person.getPid());
                if (!addrResultData.isSuccess()) {return new Result(addrResultData);}
                jsonObject.putAll((JSONObject) JSONObject.toJSON(addrResultData.getData()));
            }
            jsonArray.add(jsonObject);
        }

        return new ResultData(jsonArray);


    }


}
